<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步查询演示 (SSE版)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .query-result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
        }
        .pending {
            background-color: #fff3cd;
        }
        .completed {
            background-color: #d1e7dd;
        }
        .failed {
            background-color: #f8d7da;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1>异步查询演示 (SSE版)</h1>
        <p>本演示展示如何实现异步查询，以及如何通过Server-Sent Events (SSE)实时更新查询状态。</p>
        
        <div class="row mt-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>发起查询</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="userId" class="form-label">用户ID (1-100为有效ID)</label>
                            <input type="number" class="form-control" id="userId" value="42">
                        </div>
                        <button class="btn btn-primary" id="startQueryBtn">开始查询</button>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>查询状态</h5>
                    </div>
                    <div class="card-body">
                        <div id="queryStatus">
                            <p class="text-muted">尚未开始查询</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="mt-4">
            <h3>结果日志</h3>
            <div id="resultLog" class="border p-3 bg-light" style="max-height: 300px; overflow-y: auto;">
                <!-- 日志内容将在这里显示 -->
            </div>
        </div>
    </div>

    <!-- 引入依赖库 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    
    <script>
        $(document).ready(function() {
            let eventSource = null;
            let currentQueryId = null;
            
            // 格式化日期时间
            function formatDateTime(dateTimeStr) {
                if (!dateTimeStr) return '';
                const date = new Date(dateTimeStr);
                return date.toLocaleString();
            }
            
            // 添加日志
            function addLog(message) {
                const now = new Date().toLocaleTimeString();
                $('#resultLog').prepend(`<div class="mb-1"><small class="text-muted">${now}:</small> ${message}</div>`);
            }
            
            // 关闭之前的SSE连接
            function closeEventSource() {
                if (eventSource) {
                    eventSource.close();
                    addLog(`已关闭SSE连接: ${currentQueryId}`);
                    eventSource = null;
                }
            }
            
            // 订阅查询结果更新
            function subscribeToQueryUpdates(queryId) {
                // 关闭之前的连接
                closeEventSource();
                
                // 创建新的SSE连接
                currentQueryId = queryId;
                eventSource = new EventSource(`/api/sse/subscribe/${queryId}`);
                
                // 连接打开事件
                eventSource.onopen = function() {
                    addLog(`SSE连接已建立: ${queryId}`);
                };
                
                // 消息事件 (默认事件)
                eventSource.onmessage = function(event) {
                    const result = JSON.parse(event.data);
                    updateQueryStatus(result);
                    addLog(`收到默认消息更新: 状态=${result.status}`);
                };
                
                // 查询更新事件 (自定义事件)
                eventSource.addEventListener('query-update', function(event) {
                    const result = JSON.parse(event.data);
                    updateQueryStatus(result);
                    addLog(`收到查询结果更新: 状态=${result.status}`);
                    
                    // 如果查询完成或失败，则关闭连接
                    if (result.status === 'COMPLETED' || result.status === 'FAILED') {
                        eventSource.close();
                        eventSource = null;
                        addLog(`查询已${result.status}，SSE连接已关闭`);
                    }
                });
                
                // 错误处理
                eventSource.onerror = function(error) {
                    addLog(`SSE连接错误`);
                    eventSource.close();
                    eventSource = null;
                };
            }
            
            // 更新查询状态UI
            function updateQueryStatus(result) {
                let statusClass = '';
                switch(result.status) {
                    case 'PENDING': statusClass = 'pending'; break;
                    case 'COMPLETED': statusClass = 'completed'; break;
                    case 'FAILED': statusClass = 'failed'; break;
                }
                
                let html = `
                    <div class="query-result ${statusClass}">
                        <p><strong>查询ID:</strong> ${result.queryId}</p>
                        <p><strong>状态:</strong> ${result.status}</p>
                        <p><strong>消息:</strong> ${result.message}</p>
                        <p><strong>开始时间:</strong> ${formatDateTime(result.startTime)}</p>
                `;
                
                if (result.endTime) {
                    html += `<p><strong>结束时间:</strong> ${formatDateTime(result.endTime)}</p>`;
                }
                
                if (result.data) {
                    html += `
                        <div class="mt-3">
                            <h5>查询结果:</h5>
                            <pre>${JSON.stringify(result.data, null, 2)}</pre>
                        </div>
                    `;
                }
                
                html += `</div>`;
                
                $('#queryStatus').html(html);
            }
            
            // 启动查询
            $('#startQueryBtn').click(function() {
                const userId = $('#userId').val();
                if (!userId) {
                    alert('请输入用户ID');
                    return;
                }
                
                $(this).prop('disabled', true);
                addLog(`开始查询用户ID: ${userId}`);
                
                $.ajax({
                    url: `/api/query/start/${userId}`,
                    method: 'GET',
                    success: function(response) {
                        addLog(`查询请求已提交，查询ID: ${response.queryId}`);
                        currentQueryId = response.queryId;
                        updateQueryStatus(response);
                        
                        // 订阅SSE更新
                        subscribeToQueryUpdates(response.queryId);
                    },
                    error: function(error) {
                        addLog(`查询请求提交失败: ${error.responseText}`);
                        $('#startQueryBtn').prop('disabled', false);
                    },
                    complete: function() {
                        setTimeout(function() {
                            $('#startQueryBtn').prop('disabled', false);
                        }, 2000);
                    }
                });
            });
            
            // 页面卸载时关闭SSE连接
            $(window).on('beforeunload', function() {
                closeEventSource();
            });
        });
    </script>
</body>
</html> 